package com.hk.core.authentication.security.attempt;

import lombok.Setter;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultUserAttemptServiceImpl implements UserAttemptService {

    private final ConcurrentHashMap<String, SimpleUserAttempt> attempts = new ConcurrentHashMap<>();

    @Setter
    private int expireMinutes = 5;

    @Override
    public void updateFailAttempt(String account) {
        attempts.compute(account, (key, userAttempt) -> {
            if (Objects.isNull(userAttempt)) {
                userAttempt = new SimpleUserAttempt();
                userAttempt.setUsername(key);
                userAttempt.setAttempt(1);
            } else {
                userAttempt.setAttempt(userAttempt.getAttempt() + 1);
            }
            userAttempt.setExpireMinutes(expireMinutes);
            return userAttempt;
        });
    }

    @Override
    public void resetFailAttempt(String account) {
        attempts.remove(account);
    }

    @Override
    public Optional<UserAttempt> getUserAttempt(String account) {
        return Optional.ofNullable(attempts.get(account));
    }
}
